//
//  FXTextView.swift
//  微博(Swift)
//
//  Created by V on 16/1/7.
//  Copyright © 2016年 V. All rights reserved.
//

import UIKit

class FXTextView: UITextView {
    
    
    // 属性
    var placeholder: String? {
        didSet{
            placeholderLabel.text = placeholder
        }
    }
    override var font: UIFont? {
        didSet{
            placeholderLabel.font = font
        }
    }
    
    
    
    
    
    // 懒加载
    private lazy var placeholderLabel: UILabel = {
        let placeholderLabel = UILabel()
        placeholderLabel.font = UIFont.systemFontOfSize(12)
        placeholderLabel.text = "－你觉的这里大么？－大啊"
        // placeholderLabel.tintColor = UIColor.lightGrayColor()
        placeholderLabel.textColor = UIColor.lightGrayColor()
        placeholderLabel.numberOfLines = 0
        return placeholderLabel
    }()
    
    
    
    
    override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame: frame, textContainer: textContainer)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        placeholderLabel.frame.origin.x = 5
        placeholderLabel.frame.origin.y = 8
        // 
        placeholderLabel.frame.size = (placeholderLabel.text! as NSString).boundingRectWithSize(CGSize(width: self.frame.width - 2 * placeholderLabel.frame.origin.x, height: CGFloat(MAXFLOAT)), options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: [NSFontAttributeName: placeholderLabel.font], context: nil).size
    }
    
    
    
    
    
    private func setupUI(){
        addSubview(placeholderLabel)
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "textViewDidChanged", name: UITextViewTextDidChangeNotification, object: nil)
        
    }
    
    
    
    @objc private func textViewDidChanged(){
        placeholderLabel.hidden = self.hasText()
    }

    
    
    
    
    
    // 移除通知
    deinit{
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }

}
